package com.hongshu.idle.async;

import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.hongshu.common.core.domain.R;
import com.hongshu.common.core.enums.AuditStatusEnum;
import com.hongshu.common.core.enums.ProductTypeEnum;
import com.hongshu.common.core.enums.TerminalTypeEnum;
import com.hongshu.common.core.utils.ConvertUtils;
import com.hongshu.idle.domain.dto.ProductDTO;
import com.hongshu.idle.domain.entity.IdleProduct;
import com.hongshu.idle.domain.entity.IdleUser;
import com.hongshu.idle.mapper.idle.IdleProductMapper;
import com.hongshu.idle.mapper.idle.IdleUserMapper;
import com.hongshu.idle.service.sys.ISysSystemConfigService;
import com.hongshu.system.api.RemoteFileService;
import com.hongshu.system.api.domain.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductAsyncTask {

    @Autowired
    private IdleUserMapper userMapper;
    @Autowired
    private IdleProductMapper productMapper;
    //    @Autowired
//    private IOssService ossService;
    @Autowired
    private ISysSystemConfigService systemConfigService;
    @Autowired
    private RemoteFileService remoteFileService;


    @Async
    @Transactional(rollbackFor = Exception.class)
    public void addProduct(String terminal, String currentUid, String noteData, String coverLocalPath, List<String> fileLocalPaths) {
        try {
            // 更新用户商品数量
            IdleUser user = userMapper.selectById(currentUid);
            user.setProductCount(user.getProductCount() + 1);
            userMapper.updateById(user);

            // 保存商品
            ProductDTO productDTO = JSONUtil.toBean(noteData, ProductDTO.class);
            IdleProduct product = ConvertUtils.sourceToTarget(productDTO, IdleProduct.class);
            product.setUid(currentUid);
            product.setFromType(TerminalTypeEnum.fromValue(terminal).getCode());
            product.setAuthor(user.getUsername());
            product.setDescription(productDTO.getContent());
            product.setProductType(productDTO.getProductType());
            // 查询审核开关，是否开启审核
            Boolean idleAuditEnable = systemConfigService.getSystemConfig().getContentAuditEnabled();
            if (idleAuditEnable) {
                product.setAuditStatus(AuditStatusEnum.REVIEW.getCode());
                product.setType(ProductTypeEnum.PEND_LIST.getCode());
            } else {
                product.setAuditStatus(AuditStatusEnum.PASS.getCode());
                product.setType(ProductTypeEnum.ONLINE.getCode());
            }
            product.setCreator(user.getUsername());
            product.setCreateTime(new Date());
            product.setUpdateTime(new Date());
            try {
                // 上传封面
                if (coverLocalPath == null) {
                    throw new RuntimeException("封面文件不能为空");
                }
                File coverFile = new File(coverLocalPath);
//                String noteCover = ossService.upload(coverFile);
                R<SysFile> upload = remoteFileService.upload(coverFile);
                String noteCover = upload.getData().getUrl();
                if (noteCover == null) {
                    throw new RuntimeException("封面上传失败");
                }
                product.setCover(noteCover);
                // 根据笔记类型处理文件
                List<String> dataList = new ArrayList<>();
                if (1 == product.getProductType()) {
                    // 图片类型
                    if (fileLocalPaths == null || fileLocalPaths.size() <= 0) {
                        throw new RuntimeException("未上传任何图片");
                    }
                    List<File> files = fileLocalPaths.stream().map(File::new).collect(Collectors.toList());
                    // 批量上传图片
//                    List<String> listR = ossService.uploadBatch(files);
//                    if (listR != null) {
//                        dataList = listR;
//                    } else {
//                        throw new RuntimeException("图片上传失败");
//                    }
                    R<List<SysFile>> listR = remoteFileService.batchUpload(files);
                    List<String> urls = Optional.ofNullable(listR)
                            .filter(response -> response.getCode() == 200) // 检查成功状态
                            .map(R::getData) // 获取数据
                            .filter(CollectionUtils::isNotEmpty) // 检查数据不为空
                            .orElseThrow(() -> {
                                String errorMsg = listR != null ? listR.getMsg() : "远程服务无响应";
                                return new RuntimeException("图片上传失败: " + errorMsg);
                            })
                            .stream()
                            .map(SysFile::getUrl) // 提取URL
                            .filter(Objects::nonNull) // 过滤掉null的URL
                            .collect(Collectors.toList());
                    dataList.addAll(urls);
                } else if (2 == product.getProductType()) {
                    // 视频类型
                    if (fileLocalPaths == null || fileLocalPaths.size() <= 0) {
                        throw new RuntimeException("请上传一个视频文件");
                    }
                    // 上传视频
                    List<File> files = fileLocalPaths.stream().map(File::new).collect(Collectors.toList());
//                    String videoResult = ossService.upload(files.get(0));
                    R<SysFile> videoUpload = remoteFileService.upload(files.get(0));
                    String videoResult = videoUpload.getData().getUrl();
                    if (videoResult != null) {
                        dataList.add(videoResult);
                    } else {
                        throw new RuntimeException("视频上传失败");
                    }
                } else {
                    throw new RuntimeException("无效的笔记类型");
                }
                if (dataList.isEmpty()) {
                    throw new RuntimeException("未获取到有效的文件URL");
                }
                // 设置文件URL
                String urls = JSONUtil.toJsonStr(dataList.toArray(new String[0]));
                product.setUrls(urls);
                // 保存商品
                productMapper.insert(product);
            } catch (Exception e) {
                log.error("商品保存失败", e);
                throw new RuntimeException("商品保存失败: " + e.getMessage());
            }
        } catch (Exception e) {
            log.error("商品保存失败", e);
            // 这里可以做一些失败补偿或通知
        } finally {
            // 删除封面临时文件
            if (coverLocalPath != null) {
                File coverFile = new File(coverLocalPath);
                if (coverFile.exists()) {
                    boolean deleted = coverFile.delete();
                    if (!deleted) {
                        log.warn("封面临时文件删除失败: {}", coverLocalPath);
                    }
                }
            }
            // 删除内容文件临时文件
            if (fileLocalPaths != null) {
                for (String path : fileLocalPaths) {
                    File file = new File(path);
                    if (file.exists()) {
                        boolean deleted = file.delete();
                        if (!deleted) {
                            log.warn("内容临时文件删除失败: {}", path);
                        }
                    }
                }
            }
        }
    }

    @Async
    public void updateProduct(ProductDTO productDTO, IdleProduct product, String coverLocalPath, List<String> fileLocalPaths) {
        try {
            // 更新基本字段
            product.setTitle(productDTO.getTitle());
            product.setDescription(productDTO.getContent());
            product.setProductType(productDTO.getProductType());
            product.setPrice(productDTO.getPrice());
            product.setOriginalPrice(productDTO.getOriginalPrice());
            product.setAddress(productDTO.getAddress());
            product.setCpid(productDTO.getCpid());
            product.setCid(productDTO.getCid());
            product.setPostType(productDTO.getPostType());
            product.setUpdateTime(new Date());
            // 处理封面
            if (coverLocalPath == null) {
                throw new RuntimeException("封面文件不能为空");
            }
            File coverFile = new File(coverLocalPath);
//            String noteCover = ossService.upload(coverFile);
            R<SysFile> upload = remoteFileService.upload(coverFile);
            String noteCover = upload.getData().getUrl();
            if (noteCover == null) {
                throw new RuntimeException("封面上传失败");
            }
            product.setCover(noteCover);
            // 处理文件（图片或视频）
            List<String> dataList = new ArrayList<>();
            if (1 == productDTO.getProductType()) {
                // 图片类型
                if (fileLocalPaths == null || fileLocalPaths.size() <= 0) {
                    throw new RuntimeException("未上传任何图片");
                }
                List<File> files = fileLocalPaths.stream().map(File::new).collect(Collectors.toList());
//                List<String> listR = ossService.uploadBatch(files);
//                if (listR != null) {
//                    dataList = listR;
//                } else {
//                    throw new RuntimeException("图片上传失败");
//                }
                // 批量上传图片
                R<List<SysFile>> listR = remoteFileService.batchUpload(files);
                List<String> urls = Optional.ofNullable(listR)
                        .filter(response -> response.getCode() == 200) // 检查成功状态
                        .map(R::getData) // 获取数据
                        .filter(CollectionUtils::isNotEmpty) // 检查数据不为空
                        .orElseThrow(() -> {
                            String errorMsg = listR != null ? listR.getMsg() : "远程服务无响应";
                            return new RuntimeException("图片上传失败: " + errorMsg);
                        })
                        .stream()
                        .map(SysFile::getUrl) // 提取URL
                        .filter(Objects::nonNull) // 过滤掉null的URL
                        .collect(Collectors.toList());
                dataList.addAll(urls);

                product.setUrls(JSONUtil.toJsonStr(dataList.toArray(new String[0])));
                // 没有新图片就不动原有urls
            } else if (2 == productDTO.getProductType()) {
                // 视频类型
                if (fileLocalPaths == null || fileLocalPaths.size() <= 0) {
                    throw new RuntimeException("请上传一个视频文件");
                }
                List<File> files = fileLocalPaths.stream().map(File::new).collect(Collectors.toList());
//                String videoResult = ossService.upload(files.get(0));
                R<SysFile> videoUpload = remoteFileService.upload(files.get(0));
                String videoResult = videoUpload.getData().getUrl();
                if (videoResult != null) {
                    dataList.add(videoResult);
                    product.setUrls(JSONUtil.toJsonStr(dataList.toArray(new String[0])));
                } else {
                    throw new RuntimeException("视频上传失败");
                }
                // 没有新视频就不动原有urls
            } else {
                throw new RuntimeException("无效的商品类型");
            }
            // 审核状态处理（可选：编辑后是否重新审核）
            Boolean idleAuditEnable = systemConfigService.getSystemConfig().getContentAuditEnabled();
            if (idleAuditEnable) {
                product.setAuditStatus(AuditStatusEnum.REVIEW.getCode());
                product.setType(ProductTypeEnum.PEND_LIST.getCode());
            } else {
                product.setAuditStatus(AuditStatusEnum.PASS.getCode());
                product.setType(ProductTypeEnum.ONLINE.getCode());
            }
            // 更新数据库
            productMapper.updateById(product);
        } finally {
            // 删除封面临时文件
            if (coverLocalPath != null) {
                File coverFile = new File(coverLocalPath);
                if (coverFile.exists()) {
                    boolean deleted = coverFile.delete();
                    if (!deleted) {
                        log.warn("封面临时文件删除失败: {}", coverLocalPath);
                    }
                }
            }
            // 删除内容文件临时文件
            if (fileLocalPaths != null) {
                for (String path : fileLocalPaths) {
                    File file = new File(path);
                    if (file.exists()) {
                        boolean deleted = file.delete();
                        if (!deleted) {
                            log.warn("内容临时文件删除失败: {}", path);
                        }
                    }
                }
            }
        }
    }
}
